import requests
import execjs
from lxml import etree
from flask import Flask, jsonify, request
import time
import os
import sys
import threading

app = Flask(__name__)

session = requests.session()
headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'no-cache',
    'pragma': 'no-cache',
    'priority': 'u=0, i',
    'referer': 'https://pcticket.cstm.org.cn/team/index',
    'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'same-origin',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
    # 'cookie': 'e89geEmDI6fkO=60WU.puugLgOaRIR7K9PMWmlP3FpbrBSalRSYF3PoIwZ6pMX1hq1p1Wx5dRjAiW.RFaPMYZPMmgbpocNHpP.0XzA; e89geEmDI6fkP=0mu7Mzi1VwN.RrhpVDONls_Y8zpWX9kS9lbUQieYXw3ja.6Yhr8IuynIcedPVKQQL0Eoq2zZqzoiQ5o5eAq2VmWYKztoa6a3BHZ9R3tVm3LgCZXgmw_zwiZU8u6B9LvxMhoCSQ00b_sQwCFfHyMgiSxJvfU_3MJRr77Dw.i0lwPWvhiyNPfVjbWXfCmikKz7VOBBqrIeASag8pzXpBSIyiB7JjSV68FXbdm0RJkPR.k8hDfU_pTjDG0arVrhUDWwT0x4gThBTMaN2ONMLiTiKW2Mc3vCzyFp45vhPXHHn8Bc3h.gQCd3van1Zu1QDedGq',
}


def firstgetcontent(url, ck={}):
    response = session.get(url, cookies=ck, headers=headers)
    print(response)
    html = etree.HTML(response.text)
    meta_content = html.xpath('//meta[2]/@content')[0]
    auto_js = html.xpath('//script[1]/text()')[0]
    ts_url = 'https://pcticket.cstm.org.cn' + html.xpath('//script[2]/@src')[0]
    ts_js = session.get(ts_url).text
    return meta_content, auto_js, ts_js


def getcontent(url, ck={}):
    response = session.get(url, cookies=ck, headers=headers)
    print(response)
    html = etree.HTML(response.text)
    meta_content = html.xpath('//meta[5]/@content')[0]
    auto_js = html.xpath('//script[1]/text()')[0]
    ts_url = 'https://pcticket.cstm.org.cn' + html.xpath('//script[2]/@src')[0]
    ts_js = session.get(ts_url).text
    return meta_content, auto_js, ts_js


def update_cookie(meta_content, auto_js, ts_js):
    js_code = ''
    js_code += f'meta_content="{meta_content}"\n'
    with open('get_data.js', 'r', encoding='utf-8') as js_file:
        js_code += js_file.read() + '\n'
    js_code += auto_js + '\n'
    js_code += ts_js + '\n'
    js_code += """

    function get_cookie() {
    return document.cookie
    }

    """

    with open(file='test.js', encoding='utf-8', mode='w') as f:
        f.write(js_code)

    js_compile = execjs.compile(js_code)
    print(">>>", js_compile.call('get_cookie'))
    cookie_t = js_compile.call('get_cookie').split(';')[0].split('=')
    session.cookies.update({cookie_t[0]: cookie_t[1]})
    return session.cookies.get_dict()


def login(username, password, cookies):
    headers = {
        'accept': 'application/json',
        'accept-language': 'zh-CN,zh;q=0.9',
        'authorization': '',
        'cache-control': 'no-cache',
        'content-type': 'application/json;charset=UTF-8',
        'lang': 'zh_cn',
        'origin': 'https://pcticket.cstm.org.cn',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://pcticket.cstm.org.cn/team/index',
        'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
        # 'cookie': 'e89geEmDI6fkO=60lk5uHW83qrL_dviMW4QmC8WrXiKl1f_5nOEMTEHgj9Cpk_kmeSBsln20ISidi5wTMD5uvtRwtEJCE1X6RQI3EA; e89geEmDI6fkP=0L0IbNvxNivfgYs210xwSzHObx7JTilrrUb2p1AUhGu4jfgYDoT5P2A6gW8XK99nVbph4vuCuJ.qrZUN_6aWhrgq37PzU.uWxEjnsm3Y174g6LtdjtZzrDBe5u4Axpzm.PNkZy_kjUeWTuipU5pYoLuKHbjFxbFeMr07T6wI45egyGuASxPRvYYMr.xZL.dAHcsiXEqEjvVxb0MQHFsWOD2uUIaahGk6Za9T23_Z1rmkaQjGTQtrgplf7PlWys5_AgFRjSl2V1pidD.sEZLKZnDBQnbXyul3SJ0T4yGa1br_h3HQKkXz5PHvizHIXPceEODtMOdhJH1DOwu2dx9L.K9.lNP_fV60UZAFGtj8ZNzeHlcS2xjXacCzRSSD1IMGWO19Z_lNiVzCaJANoa86IaN9mozPgRCGTHKbxu69tEYrRHa6VBnACOU6xp1XfF2VJnddHe5LKFzz2Jq.tFfrPA7oIO3UtlVKpdDgSaSOer8g',
    }

    json_data = {
        'loginType': 1,
        'userType': '2',
        'username': username,
        'password': password,
        'loginClient': '1',
    }

    response = requests.post(
        'https://pcticket.cstm.org.cn/prod-api/login',
        cookies=cookies,
        headers=headers,
        json=json_data,
    )
    print(response.text)
    return response.json()['token']


def getuserinfo(ck, token):
    headers = {
        'accept': 'application/json',
        'accept-language': 'zh-CN,zh;q=0.9',
        'authorization': 'Bearer {}'.format(token),
        'cache-control': 'no-cache',
        'lang': 'zh_cn',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://pcticket.cstm.org.cn/team/index',
        'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
        # 'cookie': 'e89geEmDI6fkO=60a0etorhIF8r7qd2uYjWG_XaPM3kp2ujYZe4serntz4kVFpYU74ZKdTdwBU8mxOzo2tVqWvXGv94nLhGwRM5dj7veSFMKlPX6iE23QVPmvH0; e89geEmDI6fkP=0aSjXj6FrSFgKl82DSc_R1JlaMT.gYFQ8Q2ecE7OzAAQfqYsB8wSlyjHJPHjlApDsTEmTCehtcO3GNnVApOLIqfJd.mNTHfCPfG9tDQ9VvNCYOAqmuh5C7tZ2eoBvcQqqMWnvPZhBQ_TNHiJzFGhrtLybIiz7CA9Ak_GZUficTGbSd99bZxMna0J.GZfPELtJooI9gKwq1KE0vG92xLvjPwP1vbBpV5LcQoumWN4.ltjDB9N2JTCIJQwd3GVMzHztuBiLk2xgsTb46Zj21PKUNt0Re580.y9h1hTpcSveVtVm9HNJK6mPtQQEZzBhPT2U8GGwa9M61D2eJlDpF60VBZLL15URG8s6PDJlWK5Pef_NhK6VFOAh95uMc.URN3vdccHGciNznO_ZH7lvirRscxdHsZBJik289Eqxr_dZkqGU_Io1sv27lY40M8vj1vQy1WZQocDhgxqWuf1hgnemA7CIKVNQ4DngtdUFofPvIk7',
    }
    response = requests.get(
        'https://pcticket.cstm.org.cn/prod-api/getUserInfoToTeam',
        cookies=ck,
        headers=headers,
    )
    print(response.text)


@app.route('/getcookie')
def home():
    url = 'https://pcticket.cstm.org.cn/team/index'
    meta_content, auto_js, ts_js = firstgetcontent(url)  # 易语言自己写 取里面的内容
    ck = update_cookie(meta_content, auto_js, ts_js)
    session.close()
    return jsonify(ck)


if __name__ == '__main__':
    # 第一次返回错误的页面
    url = 'https://pcticket.cstm.org.cn/team/index'
    meta_content, auto_js, ts_js = firstgetcontent(url)  # 易语言自己写 取里面的内容
    ck = update_cookie(meta_content, auto_js, ts_js)
    print(ck)
    # ck=requests.get('http://127.0.0.1:5000/getcookie').json()
    # print(ck)
    # print('=========================================================')
    # ck = requests.get('http://127.0.0.1:5000/getcookie').json()

    token = login('913711027207426863', 'kjg123456', ck)
    print(token)
    # print('=========================================================')
    ck = requests.get('http://127.0.0.1:5000/getcookie').json()
    print(ck)
    getuserinfo(ck, token)
    app.run(debug=True)
